<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>书单详情 - ZLibLike平台</title>
    <link rel="stylesheet" href="/css/bootstrap.min.css">
    <link rel="stylesheet" href="/css/bootstrap-icons.css">
    <link rel="stylesheet" href="/css/style.css">
</head>
<body>
    <div th:replace="~{commons/header :: header}"></div>
    
    <div class="container mt-4">
        <!-- 书单基本信息 -->
        <div id="bookListInfo" class="card mb-4 shadow-sm">
            <div class="card-body">
                <div class="d-flex justify-content-between align-items-start mb-2">
                    <h1 id="bookListTitle" class="mb-0 card-title">加载中...</h1>
                    <span id="bookListVisibility" class="badge badge-info">公开</span>
                </div>
                <div class="mb-3">
                    <small class="text-muted">
                        <span>创建者: <span id="bookListCreator">加载中...</span></span>
                        <span class="mx-2">|</span>
                        <span>创建时间: <span id="bookListCreateTime">加载中...</span></span>
                    </small>
                </div>
                <p id="bookListDescription" class="card-text mb-4">加载中...</p>
                
                <div id="bookListActions" class="d-none">
                    <a id="editBookListBtn" href="#" class="btn btn-outline-primary btn-sm me-2">
                        <i class="bi bi-pencil"></i> 编辑书单
                    </a>
                    <button id="deleteBookListBtn" class="btn btn-outline-danger btn-sm">
                        <i class="bi bi-trash"></i> 删除书单
                    </button>
                </div>
            </div>
        </div>
        
        <!-- 添加书籍和搜索区域 -->
        <div class="row mb-4">
            <div class="col-md-6">
                <button id="addBookBtn" class="btn btn-primary">
                    <i class="bi bi-plus-circle"></i> 添加书籍
                </button>
            </div>
            <div class="col-md-6">
                <div class="input-group">
                    <input type="text" id="searchInput" class="form-control" placeholder="搜索书籍...">
                    <div class="input-group-append">
                        <button id="searchBtn" class="btn btn-outline-secondary">
                            <i class="bi bi-search"></i> 搜索
                        </button>
                    </div>
                </div>
            </div>
        </div>
        
        <!-- 书籍列表 -->
        <div id="bookList" class="row">
            <div class="col-12 text-center py-5">
                <div class="spinner-border" role="status">
                    <span class="sr-only">加载中...</span>
                </div>
            </div>
        </div>
        
        <!-- 分页控件 -->
        <div id="pagination" class="d-flex justify-content-center mt-4"></div>
    </div>
    
    <!-- 添加书籍模态框 -->
    <div class="modal fade" id="addBookModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog modal-lg" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">添加书籍到书单</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="关闭">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <div class="form-group mb-3">
                        <div class="input-group">
                            <input type="text" id="bookSearchInput" class="form-control" placeholder="搜索书籍标题、作者或ISBN...">
                            <div class="input-group-append">
                                <button id="bookSearchBtn" class="btn btn-outline-secondary">
                                    <i class="bi bi-search"></i> 搜索
                                </button>
                            </div>
                        </div>
                    </div>
                    
                    <div id="searchResults" class="row">
                        <div class="col-12 text-center py-4">
                            <p class="text-muted">请输入搜索关键词查找书籍</p>
                        </div>
                    </div>
                    
                    <div id="searchPagination" class="d-flex justify-content-center mt-3"></div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">关闭</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 书籍备注编辑模态框 -->
    <div class="modal fade" id="editNoteModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">编辑书籍备注</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="关闭">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <input type="hidden" id="editNoteBookItemId">
                    <div class="form-group">
                        <label for="noteContent">个人备注</label>
                        <textarea class="form-control" id="noteContent" rows="4" maxlength="500" placeholder="添加您对这本书的想法、推荐理由或阅读心得..."></textarea>
                        <small class="form-text text-muted">最多500个字符</small>
                    </div>
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-primary" id="saveNoteBtn">保存</button>
                </div>
            </div>
        </div>
    </div>
    
    <!-- 确认删除模态框 -->
    <div class="modal fade" id="confirmDeleteModal" tabindex="-1" role="dialog" aria-hidden="true">
        <div class="modal-dialog" role="document">
            <div class="modal-content">
                <div class="modal-header">
                    <h5 class="modal-title">确认删除</h5>
                    <button type="button" class="close" data-dismiss="modal" aria-label="关闭">
                        <span aria-hidden="true">&times;</span>
                    </button>
                </div>
                <div class="modal-body">
                    <p id="deleteConfirmMessage">您确定要删除这个书单吗？此操作无法撤销。</p>
                    <input type="hidden" id="deleteItemId" value="">
                    <input type="hidden" id="deleteType" value="">
                </div>
                <div class="modal-footer">
                    <button type="button" class="btn btn-secondary" data-dismiss="modal">取消</button>
                    <button type="button" class="btn btn-danger" id="confirmDeleteBtn">删除</button>
                </div>
            </div>
        </div>
    </div>
    
    <div th:replace="~{commons/footer :: footer}"></div>
    
    <script src="/js/jquery-3.6.0.min.js"></script>
    <script src="/js/bootstrap.bundle.min.js"></script>
    <script th:inline="javascript">
        $(document).ready(function() {
            // 获取书单ID
            const urlParams = new URLSearchParams(window.location.search);
            const bookListId = urlParams.get('id');
            
            if (!bookListId) {
                window.location.href = '/book-lists.html';
                return;
            }
            
            // 当前页码
            let currentPage = 1;
            let searchCurrentPage = 1;
            const pageSize = 12;
            
            // 加载书单信息
            loadBookListInfo();
            
            // 加载书籍列表
            loadBooks();
            
            // 添加书籍按钮点击事件
            $('#addBookBtn').click(function() {
                $('#bookSearchInput').val('');
                $('#searchResults').html(`
                    <div class="col-12 text-center py-4">
                        <p class="text-muted">请输入搜索关键词查找书籍</p>
                    </div>
                `);
                $('#searchPagination').html('');
                $('#addBookModal').modal('show');
            });
            
            // 搜索书单内书籍
            $('#searchBtn').click(function() {
                currentPage = 1;
                loadBooks();
            });
            
            $('#searchInput').keypress(function(e) {
                if (e.which === 13) {
                    currentPage = 1;
                    loadBooks();
                }
            });
            
            // 搜索要添加的书籍
            $('#bookSearchBtn').click(function() {
                searchCurrentPage = 1;
                searchBooks();
            });
            
            $('#bookSearchInput').keypress(function(e) {
                if (e.which === 13) {
                    searchCurrentPage = 1;
                    searchBooks();
                }
            });
            
            // 编辑备注保存按钮
            $('#saveNoteBtn').click(function() {
                saveNote();
            });
            
            // 确认删除按钮
            $('#confirmDeleteBtn').click(function() {
                const type = $('#deleteType').val();
                const itemId = $('#deleteItemId').val();
                
                if (type === 'book-list') {
                    deleteBookList();
                } else if (type === 'book-item') {
                    removeBookFromList(itemId);
                }
            });
            
            // 删除书单按钮
            $('#deleteBookListBtn').click(function() {
                $('#deleteType').val('book-list');
                $('#deleteConfirmMessage').text('您确定要删除这个书单吗？此操作无法撤销。');
                $('#confirmDeleteModal').modal('show');
            });
            
            // 编辑书单按钮
            $('#editBookListBtn').click(function() {
                window.location.href = `/book-list-edit.html?id=${bookListId}`;
            });
            
            // 加载书单基本信息
            function loadBookListInfo() {
                fetch(`/api/book-lists/${bookListId}`)
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 200) {
                            const bookList = data.data;
                            
                            // 更新书单信息
                            $('#bookListTitle').text(bookList.title);
                            $('#bookListDescription').text(bookList.description || '暂无描述');
                            $('#bookListCreator').text(bookList.creatorName);
                            $('#bookListCreateTime').text(new Date(bookList.createTime).toLocaleString());
                            
                            // 设置可见性标签
                            const visibilityBadge = bookList.isPublic ? 
                                '<span class="badge badge-info">公开</span>' : 
                                '<span class="badge badge-secondary">私人</span>';
                            $('#bookListVisibility').html(visibilityBadge);
                            
                            // 如果是创建者，显示编辑和删除按钮
                            if (bookList.isCreator) {
                                $('#bookListActions').removeClass('d-none');
                            }
                            
                            // 更新页面标题
                            document.title = `${bookList.title} - 书单详情 - ZLibLike平台`;
                        } else {
                            alert('加载书单信息失败: ' + data.message);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        alert('加载书单信息失败，请稍后重试');
                    });
            }
            
            // 加载书单中的书籍
            function loadBooks() {
                const keyword = $('#searchInput').val().trim();
                const url = `/api/book-lists/${bookListId}/books?page=${currentPage}&size=${pageSize}${keyword ? '&keyword=' + encodeURIComponent(keyword) : ''}`;
                
                $('#bookList').html(`
                    <div class="col-12 text-center py-5">
                        <div class="spinner-border" role="status">
                            <span class="sr-only">加载中...</span>
                        </div>
                    </div>
                `);
                
                fetch(url)
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 200) {
                            renderBookList(data.data);
                        } else {
                            $('#bookList').html(`
                                <div class="col-12 text-center py-5">
                                    <p class="text-muted">加载失败: ${data.message || '未知错误'}</p>
                                </div>
                            `);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        $('#bookList').html(`
                            <div class="col-12 text-center py-5">
                                <p class="text-muted">加载失败，请稍后重试</p>
                            </div>
                        `);
                    });
            }
            
            // 渲染书籍列表
            function renderBookList(data) {
                const books = data.content;
                const totalPages = data.totalPages;
                const isCreator = data.isCreator;
                
                if (books.length === 0) {
                    $('#bookList').html(`
                        <div class="col-12 text-center py-5">
                            <p class="text-muted">书单中暂无书籍</p>
                        </div>
                    `);
                    $('#pagination').html('');
                    return;
                }
                
                let html = '';
                
                books.forEach(book => {
                    const coverUrl = book.coverUrl || '/images/default-cover.jpg';
                    
                    html += `
                        <div class="col-md-6 col-lg-4 mb-4">
                            <div class="card h-100 shadow-sm">
                                <div class="row no-gutters">
                                    <div class="col-4">
                                        <img src="${coverUrl}" class="card-img" alt="${book.title}" style="height: 100%; object-fit: cover;">
                                    </div>
                                    <div class="col-8">
                                        <div class="card-body">
                                            <h5 class="card-title text-truncate">
                                                <a href="/book-detail.html?id=${book.bookId}" class="text-decoration-none">${book.title}</a>
                                            </h5>
                                            <p class="card-text text-truncate">${book.author}</p>
                                            <p class="card-text"><small class="text-muted">${book.publisher || ''}</small></p>
                                        </div>
                                    </div>
                                </div>
                                
                                ${book.note ? `
                                <div class="card-footer">
                                    <p class="mb-2 text-muted"><small>个人备注:</small></p>
                                    <p class="card-text mb-2"><small>${book.note}</small></p>
                                </div>
                                ` : ''}
                                
                                ${isCreator ? `
                                <div class="card-footer bg-white">
                                    <button class="btn btn-sm btn-outline-primary edit-note" data-id="${book.id}">
                                        <i class="bi bi-pencil"></i> ${book.note ? '编辑备注' : '添加备注'}
                                    </button>
                                    <button class="btn btn-sm btn-outline-danger remove-book ms-2" data-id="${book.id}">
                                        <i class="bi bi-trash"></i> 移除
                                    </button>
                                </div>
                                ` : ''}
                            </div>
                        </div>
                    `;
                });
                
                $('#bookList').html(html);
                renderPagination(totalPages, currentPage, 'main');
                
                // 绑定编辑备注按钮点击事件
                $('.edit-note').click(function() {
                    const itemId = $(this).data('id');
                    const book = books.find(b => b.id === itemId);
                    
                    $('#editNoteBookItemId').val(itemId);
                    $('#noteContent').val(book.note || '');
                    $('#editNoteModal').modal('show');
                });
                
                // 绑定移除书籍按钮点击事件
                $('.remove-book').click(function() {
                    const itemId = $(this).data('id');
                    $('#deleteType').val('book-item');
                    $('#deleteItemId').val(itemId);
                    $('#deleteConfirmMessage').text('您确定要从书单中移除这本书吗？');
                    $('#confirmDeleteModal').modal('show');
                });
            }
            
            // 搜索要添加的书籍
            function searchBooks() {
                const keyword = $('#bookSearchInput').val().trim();
                
                if (!keyword) {
                    $('#searchResults').html(`
                        <div class="col-12 text-center py-4">
                            <p class="text-muted">请输入搜索关键词查找书籍</p>
                        </div>
                    `);
                    $('#searchPagination').html('');
                    return;
                }
                
                $('#searchResults').html(`
                    <div class="col-12 text-center py-4">
                        <div class="spinner-border" role="status">
                            <span class="sr-only">搜索中...</span>
                        </div>
                    </div>
                `);
                
                const url = `/api/books/search?keyword=${encodeURIComponent(keyword)}&page=${searchCurrentPage}&size=${pageSize}`;
                
                fetch(url)
                    .then(response => response.json())
                    .then(data => {
                        if (data.status === 200) {
                            renderSearchResults(data.data);
                        } else {
                            $('#searchResults').html(`
                                <div class="col-12 text-center py-4">
                                    <p class="text-muted">搜索失败: ${data.message || '未知错误'}</p>
                                </div>
                            `);
                        }
                    })
                    .catch(error => {
                        console.error('Error:', error);
                        $('#searchResults').html(`
                            <div class="col-12 text-center py-4">
                                <p class="text-muted">搜索失败，请稍后重试</p>
                            </div>
                        `);
                    });
            }
            
            // 渲染搜索结果
            function renderSearchResults(data) {
                const books = data.content;
                const totalPages = data.totalPages;
                
                if (books.length === 0) {
                    $('#searchResults').html(`
                        <div class="col-12 text-center py-4">
                            <p class="text-muted">未找到相关书籍</p>
                        </div>
                    `);
                    $('#searchPagination').html('');
                    return;
                }
                
                let html = '';
                
                books.forEach(book => {
                    const coverUrl = book.coverUrl || '/images/default-cover.jpg';
                    const isInBookList = book.isInBookList;
                    
                    html += `
                        <div class="col-md-6 mb-3">
                            <div class="card h-100">
                                <div class="row no-gutters">
                                    <div class="col-4">
                                        <img src="${coverUrl}" class="card-img" alt="${book.title}" style="height: 100%; object-fit: cover;">
                                    </div>
                                    <div class="col-8">
                                        <div class="card-body">
                                            <h5 class="card-title text-truncate">${book.title}</h5>
                                            <p class="card-text text-truncate">${book.author}</p>
                                            <p class="card-text"><small class="text-muted">${book.publisher || ''}</small></p>
                                            
                                            ${isInBookList ? 
                                                `<button class="btn btn-sm btn-secondary" disabled>已添加</button>` : 
                                                `<button class="btn btn-sm btn-primary add-book" data-id="${book.id}">添加</button>`
                                            }
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    `;
                });
                
                $('#searchResults').html(html);
                renderPagination(totalPages, searchCurrentPage, 'search');
                
                // 绑定添加书籍按钮点击事件
                $('.add-book').click(function() {
                    const bookId = $(this).data('id');
                    addBookToList(bookId, $(this));
                });
            }
            
            // 添加书籍到书单
            function addBookToList(bookId, buttonElement) {
                buttonElement.prop('disabled', true).text('添加中...');
                
                fetch(`/api/book-lists/${bookListId}/books`, {
                    method: 'POST',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ bookId: bookId })
                })
                .then(response => response.json())
                .then(data => {
                    if (data.status === 200) {
                        buttonElement.removeClass('btn-primary').addClass('btn-secondary').text('已添加');
                    } else {
                        buttonElement.prop('disabled', false);
                        alert('添加失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    buttonElement.prop('disabled', false);
                    alert('添加过程中发生错误，请稍后重试');
                });
            }
            
            // 从书单中移除书籍
            function removeBookFromList(itemId) {
                fetch(`/api/book-lists/${bookListId}/books/${itemId}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    $('#confirmDeleteModal').modal('hide');
                    
                    if (data.status === 200) {
                        loadBooks();
                    } else {
                        alert('移除失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    $('#confirmDeleteModal').modal('hide');
                    alert('移除过程中发生错误，请稍后重试');
                });
            }
            
            // 保存书籍备注
            function saveNote() {
                const itemId = $('#editNoteBookItemId').val();
                const note = $('#noteContent').val().trim();
                
                fetch(`/api/book-lists/${bookListId}/books/${itemId}/note`, {
                    method: 'PUT',
                    headers: {
                        'Content-Type': 'application/json'
                    },
                    body: JSON.stringify({ note: note })
                })
                .then(response => response.json())
                .then(data => {
                    $('#editNoteModal').modal('hide');
                    
                    if (data.status === 200) {
                        loadBooks();
                    } else {
                        alert('保存备注失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    $('#editNoteModal').modal('hide');
                    alert('保存备注过程中发生错误，请稍后重试');
                });
            }
            
            // 删除整个书单
            function deleteBookList() {
                fetch(`/api/book-lists/${bookListId}`, {
                    method: 'DELETE'
                })
                .then(response => response.json())
                .then(data => {
                    $('#confirmDeleteModal').modal('hide');
                    
                    if (data.status === 200) {
                        alert('书单已成功删除');
                        window.location.href = '/book-lists.html';
                    } else {
                        alert('删除失败: ' + data.message);
                    }
                })
                .catch(error => {
                    console.error('Error:', error);
                    $('#confirmDeleteModal').modal('hide');
                    alert('删除过程中发生错误，请稍后重试');
                });
            }
            
            // 渲染分页
            function renderPagination(totalPages, currentPage, type) {
                const container = type === 'main' ? $('#pagination') : $('#searchPagination');
                
                if (totalPages <= 1) {
                    container.html('');
                    return;
                }
                
                let html = `
                    <nav>
                        <ul class="pagination">
                            <li class="page-item ${currentPage === 1 ? 'disabled' : ''}">
                                <a class="page-link" href="#" data-page="${currentPage - 1}" aria-label="上一页">
                                    <span aria-hidden="true">&laquo;</span>
                                </a>
                            </li>
                `;
                
                const maxPages = 5;
                let startPage = Math.max(1, currentPage - Math.floor(maxPages / 2));
                let endPage = Math.min(totalPages, startPage + maxPages - 1);
                
                if (endPage - startPage + 1 < maxPages) {
                    startPage = Math.max(1, endPage - maxPages + 1);
                }
                
                for (let i = startPage; i <= endPage; i++) {
                    html += `
                        <li class="page-item ${i === currentPage ? 'active' : ''}">
                            <a class="page-link" href="#" data-page="${i}">${i}</a>
                        </li>
                    `;
                }
                
                html += `
                            <li class="page-item ${currentPage === totalPages ? 'disabled' : ''}">
                                <a class="page-link" href="#" data-page="${currentPage + 1}" aria-label="下一页">
                                    <span aria-hidden="true">&raquo;</span>
                                </a>
                            </li>
                        </ul>
                    </nav>
                `;
                
                container.html(html);
                
                // 绑定分页点击事件
                container.find('.page-link').click(function(e) {
                    e.preventDefault();
                    const page = parseInt($(this).data('page'));
                    
                    if (type === 'main') {
                        currentPage = page;
                        loadBooks();
                    } else {
                        searchCurrentPage = page;
                        searchBooks();
                    }
                });
            }
        });
    </script>
</body>
</html> 